package com.webapp.controller;

import java.io.IOException;
import java.util.ArrayList;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.webapp.model.Application;
import com.webapp.model.ViewTableModel;

/**
 * Servlet implementation class SortServlet.
 * Used to sort application table.
 */
public class SortServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public SortServlet() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException 
	{
		// Retrieve session.
		HttpSession session = request.getSession();
		
		// Retrieve first sort attribute.
		String firstSortValue = (String)request.getParameter("sort_list1");
		
		// Retrieve second sort attribute.
		String secondSortValue = (String)request.getParameter("sort_list2");
		
		// Retrieve filtered list.
		ArrayList<Application> filteredList = ViewTableModel.insertionSort(firstSortValue, secondSortValue, ViewTableModel.getTable());
		
		if (filteredList != null || !(firstSortValue.equals("none") && secondSortValue.equals("none")))
		{
				// Set it as new table.
				session.setAttribute("Table", filteredList);
				
				// Retrieve dispatcher.
				RequestDispatcher dispatcher = getServletContext().getRequestDispatcher("/viewApps.jsp");
				
				// Forward request.
				dispatcher.forward(request, response);
		} else {
			// Restore original table.
			session.setAttribute("Table", ViewTableModel.getTable());
		}
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
	}

}
